﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using dbPoll_Application.Models;

namespace dbPoll_Application.Helpers
{
    public static class SecurityHelper
    {
        public static Boolean CanEditQuestion(User user, Poll poll, Question question)
        {
            if (poll.isTestPoll)
            {
                return true;
            }
            if (question == null)
            {
                if (user.Roles.Contains(new Role("Poll Master")))
                {
                    return true;
                }
                else {
                    return false;
                }
            }
            foreach (var managedPoll in user.ManagedPolls)
            {
                if (managedPoll.questions.Contains(question))
                {
                    return true;
                }
            }
            foreach (var createdPoll in user.CreatedPolls)
            {
                if (createdPoll.questions.Contains(question))
                {
                    return true;
                }
            }
            if (poll.pollMasters.Contains(user))
            {
                return true;
            }
            return false;
        }

        public static Boolean CanAddQuestion(User user, Poll poll)
        {
            foreach (var item in user.CreatedPolls)
            {
                if (item == poll)
                {
                    return true;
                }
            }
            return false;
        }

        public static ICollection<Role> GetRolesForPole(User user, Poll poll)
        {
            var roles = new HashSet<Role>();
            if (user.ManagedPolls.Contains(poll))
            {
                roles.Add(new Role("Poll Administrator"));
            }
            if (user.CreatedPolls.Contains(poll))
            {
                roles.Add(new Role("Poll Creator"));
            }
            if (poll.pollMasters.Contains(user))
            {
                roles.Add(new Role("Poll Master"));
            }
            return roles;
        }
    }
}
